package icu.zqyhdm.commonService.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import icu.zqyhdm.commonService.service.MessageService;
import icu.zqyhdm.commonService.utils.ConstanSdktPropertiesUtils;
import icu.zqyhdm.exception.MyException;
import icu.zqyhdm.result.ResultCodeEnum;
import icu.zqyhdm.utils.RandomUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lifu
 * @Date 2021/7/9 20:12
 */
@Service
public class MessageServiceImpl implements MessageService {

    /**
     * 发送手机验证码接口，返回验证码，将验证码存进redi的过程有调用该服务的业务实现
     */
    @Override
    public String send(String phone) {
        //生成验证码
        String code = RandomUtil.getSixBitRandom();

        //整合阿里云的短信服务
        DefaultProfile profile = DefaultProfile.
                getProfile(ConstanSdktPropertiesUtils.REGION_Id,
                        ConstanSdktPropertiesUtils.ACCESS_KEY_ID,
                        ConstanSdktPropertiesUtils.SECRECT);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "Java后台开发日记");
        //模板code
        request.putQueryParameter("TemplateCode", "SMS_217220604");
        //验证码  使用json格式   {"code":"123456"}
        Map<String,Object> param = new HashMap();
        param.put("code",code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            if(response.getHttpResponse().isSuccess()){
                return code;
            };
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
}
